using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Xsl;
using Mvp.Xml.Common.Xsl;

namespace iNSISt
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine(
                    "Wrong number of arguments.\n\n" +
                    "Usage: " + Assembly.GetExecutingAssembly().GetName().Name + " input-file-uri output-file-uri\n\n" +
                    "  input-file-URI    File path or URL of XML input file\n" +
                    "  output-file-URI   File path or URL of NSIS script output file\n"
                );

                return;
            }

            string targetNamespace = "urn:iNSISt:schemas:code-generation-1.0";
            string schemaUri = "insist.xsd";
            string xsltDocUri = "insist.xslt";

            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas.Add(targetNamespace, schemaUri);
                settings.ValidationEventHandler += settings_ValidationEventHandler;

                using (XmlReader reader = XmlReader.Create(args[0], settings))
                {
                    MvpXslTransform xslt = new MvpXslTransform();
                    xslt.Load(xsltDocUri);
                    xslt.Transform(new XmlInput(reader), null, new XmlOutput(args[1]));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught exception: " + ex.ToString());
            }
        }

        /// <summary>
        /// Occurs when the XML input document cannot be successfully
        /// validated against the associated schema.
        /// </summary>
        static void settings_ValidationEventHandler(
            object sender, System.Xml.Schema.ValidationEventArgs e)
        {
            Console.WriteLine(
                "Input document failed schema validation with the following error:\n" +
                e.Exception.ToString());
        }
    }
}
